package com.ruoyi.business.app.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.business.app.bo.HcxAppUserCardbankBo;
import com.ruoyi.business.app.service.IMyWalletService;
import com.ruoyi.business.domain.HcxAppUser;
import com.ruoyi.business.domain.HcxAppUserCardbank;
import com.ruoyi.business.domain.HcxWithdrawApply;
import com.ruoyi.business.enums.TxTypeEnum;
import com.ruoyi.business.enums.WithdrawEnum;
import com.ruoyi.business.mapper.HcxAppUserCardbankMapper;
import com.ruoyi.business.mapper.HcxAppUserMapper;
import com.ruoyi.business.mapper.HcxWithdrawApplyMapper;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.utils.AssertUtils;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.mapper.SysConfigMapper;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * 用户Service业务层处理
 *
 * @author wsdz
 * @date 2022-08-17
 */
@Service
@AllArgsConstructor
public class MyWalletServiceImpl implements IMyWalletService {
    private final HcxAppUserCardbankMapper userbankCardMapper;

    private final HcxAppUserMapper hcxAppUserMapper;

    private final HcxWithdrawApplyMapper applyMapper;

    private final SysConfigMapper configMapper;


    @Override
    public int bankCardBind(HcxAppUserCardbankBo bo) {
        AssertUtils.isTrue(PhoneUtil.isMobile(bo.getPhonenumber()), "手机格式不合法，请检查");
        HcxAppUserCardbank card = new HcxAppUserCardbank();
        card.setUserId(SecurityUtils.getUserId());
        card.setBankCardNo(bo.getBankCardNo());
        card.setBankName("支付宝");
        card.setBankCardUserName(bo.getUserName());
        card.setPhonenumber(bo.getPhonenumber());
        return userbankCardMapper.insert(card);
    }


    @Override
    @Transactional
    public AjaxResult apply(BigDecimal amt, String type, String txType) {
        Long userId = SecurityUtils.getUserId();
        // 查询当前用户
        HcxAppUser hcxAppUser = hcxAppUserMapper.selectById(userId);
        // 如果是支付宝提现 则判断有没有绑定支付宝账号
        if (TxTypeEnum.ZIHFUBAO.getValue().equals(txType)) {
            LambdaQueryWrapper query = new LambdaQueryWrapper<HcxAppUserCardbank>().eq(HcxAppUserCardbank::getUserId, userId);
            Integer shuliang = userbankCardMapper.selectCount(query);
            if (shuliang == 0) {
                return AjaxResult.error(211, "没绑定支付宝,请检查");
            }
        }
        // 如果是微信提现 判断用户是否已微信授权(是否存在openId)
        if (TxTypeEnum.WEIXIN.getValue().equals(txType)) {
            if (StrUtil.isEmpty(hcxAppUser.getOpenId())) {
                return AjaxResult.error(212, "未进行微信授权,请检查");
            }
        }


        // 手续费比例
        SysConfig sysConfig = configMapper.selectOne(new LambdaQueryWrapper<SysConfig>().
                select(SysConfig::getConfigValue).eq(SysConfig::getConfigKey, Constants.WITHDRAW_FEE_PROPORTION));
        AssertUtils.isTrue(StrUtil.isNotEmpty(sysConfig.getConfigValue()), "请现在后台配置手续费");

        // 计算手续费
        BigDecimal feeProportion = new BigDecimal(sysConfig.getConfigValue());
        BigDecimal shouxufei = amt.multiply(feeProportion.divide(new BigDecimal(100))).setScale(2, BigDecimal.ROUND_HALF_UP);

        // 如果是余额提现

        BigDecimal beforeAmount = BigDecimal.ZERO;
        if (WithdrawEnum.YETX.getValue().equals(type)) {
            // 余额要 >= 提现金额+手续费
            AssertUtils.isTrue(hcxAppUser.getBalancePrice().compareTo(amt.add(shouxufei)) >= 0, "余额不足");
            beforeAmount = hcxAppUser.getBalancePrice();
            // 用户余额减少
            hcxAppUser.setBalancePrice(hcxAppUser.getBalancePrice().subtract(amt.add(shouxufei)));
        } else if (WithdrawEnum.TGJTX.getValue().equals(type)) {
            // 推广余额 >= 提现金额+手续费
            AssertUtils.isTrue(hcxAppUser.getSharePrice().compareTo(amt.add(shouxufei)) >= 0, "余额不足");
            beforeAmount = hcxAppUser.getSharePrice();
            // 用户余额减少
            hcxAppUser.setSharePrice(hcxAppUser.getSharePrice().subtract(amt.add(shouxufei)));
        } else if (WithdrawEnum.MDSRTX.getValue().equals(type)) {
            // 门店收入余额 >= 提现金额+手续费
            AssertUtils.isTrue(hcxAppUser.getMerchantPrice().compareTo(amt.add(shouxufei)) >= 0, "余额不足");
            beforeAmount = hcxAppUser.getMerchantPrice();
            // 用户余额减少
            hcxAppUser.setMerchantPrice(hcxAppUser.getMerchantPrice().subtract(amt.add(shouxufei)));
        }

        // 用户余额减少 审核拒绝后 余额再加回去
        hcxAppUserMapper.updateById(hcxAppUser);

        // 保存提现申请
        HcxWithdrawApply apply = new HcxWithdrawApply();
        apply.setUserId(userId);
        apply.setUserName(hcxAppUser.getUserName());
        apply.setNickName(hcxAppUser.getNickName());
        apply.setPhonenumber(hcxAppUser.getPhonenumber());
        apply.setRealName(hcxAppUser.getRealName());
        apply.setAmount(amt);
        apply.setServiceFeeProportion(feeProportion);

        // 提现前钱包金额
        apply.setBeforeAmount(beforeAmount);

        // 如果是支付宝
        if (TxTypeEnum.ZIHFUBAO.getValue().equals(txType)) {
            HcxAppUserCardbank hcxAppUserCardbank = userbankCardMapper.selectOne(new LambdaQueryWrapper<HcxAppUserCardbank>().eq(HcxAppUserCardbank::getUserId, userId));
            if (ObjectUtil.isNotEmpty(hcxAppUserCardbank)) {
                apply.setBankCardId(hcxAppUserCardbank.getId());
                apply.setBankName(hcxAppUserCardbank.getBankName());
                apply.setBankCardNo(hcxAppUserCardbank.getBankCardNo());
                apply.setBankCardUserName(hcxAppUserCardbank.getBankCardUserName());
                apply.setBankCardUserPhone(hcxAppUserCardbank.getPhonenumber());
            }
        } else {
            apply.setBankName("微信");
            apply.setBankCardNo(hcxAppUser.getOpenId());
        }
        apply.setApplyStatus(Constants.ZERO);
        apply.setTxType(type);
        apply.setServiceCharge(shouxufei);
        int insert = applyMapper.insert(apply);
        return AjaxResult.success(insert);
    }
}
